﻿using HpxWMS_Api.Models;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace HpxWMS_Api.Tools
{
    /// <summary>
    /// jwt管理器
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class JwtHelper<T>
    {

        /// <summary>
        /// 密钥
        /// </summary>
        private static readonly string secret = "qzjmc";


        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="data">存入的数据，不要放敏感数据</param>
        /// <returns></returns>
        public static string MackJwt(T data)
        {
            byte[] key = Encoding.UTF8.GetBytes(secret);
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
            IJsonSerializer serializer = new JsonNetSerializer();//序列化Json
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);//JWT编码
            return encoder.Encode(data, key);//生成令牌
        }

        /// <summary>
        /// 解析，返回解析后，token内存的数据
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static T AnalyzeJwt(string token)
        {
            byte[] key = Encoding.UTF8.GetBytes(secret);
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
            // 因为转换的时候，有可能出现异常，所以如果出现异常则返回T类型的默认值
            try
            {
                return decoder.DecodeToObject<T>(token, key, true);
            }
            catch (Exception)
            {
                return default;
            }
        }



    }
}